# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['PromAlarmRecord']

class PromAlarmRecord(Base, SessionMixin):
    '''
    告警记录
    '''
    __tablename__ = "prom_alarm_record"
    name = Column(String(256), nullable=False, comment='告警记录名称')
    # host主机 or k8s容器
    classes = Column(String(128), nullable=False, index=True, comment='规则分类')
    # firing / resolved
    status = Column(String(16), nullable=False, index=True, comment='告警状态')
    target = Column(String(128), nullable=False, index=True, comment='监控目标')
    # true/false
    state = Column(Boolean, default=text('true'), nullable=False, comment='通知状态')
    number = Column(Integer, nullable=False, comment='告警次数')
    fingerprint = Column(String(64), nullable=False, index=True, comment='告警指纹')
    notice_teams_uuid = Column(JSON, nullable=False, default=[], comment='通知小组')
    notice_count = Column(Integer, nullable=True, comment='告警已通知的次数')
    labels = Column(JSON, nullable=False, default={},comment='告警标签')
    annotations = Column(JSON, nullable=False, default={}, comment='附加信息')
    starts_at = Column(DateTime, nullable=True, comment='告警开始时间')
    ends_at = Column(DateTime, nullable=True, comment='告警结束时间')
    update_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=True, comment='告警记录说明')


    __table_args__ = (
        Index('idx_prom_alarm_record_name', 'name'),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<prom_alarm_record='{self.name}>"

    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }

        return result


    @classmethod
    def get_object_info_by_fingerprint(cls, db: Session, name: str, fingerprint: str):
        """
        根据告警指纹查找正在告警的记录
        """
        object_info = db.query(cls).filter(
            cls.name == name,
            cls.fingerprint == fingerprint,
            cls.status == "firing"
        ).to_dict_first()
        return object_info


    @classmethod
    def get_object_info_for_watchdog(cls, db: Session):
        """
        获取WatchDog的告警记录
        """
        object_info = db.query(cls).filter(
            cls.name == "PrometheusComponentsWatchDog",
            cls.status == "firing"
        ).order_by(cls.update_at.desc()).to_dict()
        if not object_info:
            return {}
        return object_info[0]


    @classmethod
    def get_object_info_for_block_global(cls, db: Session):
        """
        获取屏蔽全局告警的记录
        """
        object_info = db.query(cls).filter(
            cls.name == "BlockGlobalAlarm"
        ).to_dict_first()
 
        return object_info


    @classmethod
    def get_object_info_for_firing(cls, db: Session):
        """
        获取还在告警，没有恢复的告警记录
        """
        object_info = db.query(cls).filter(
            cls.status == "firing"
        ).order_by(cls.update_at.desc()).to_dict()
        return object_info


    @classmethod
    def get_object_info_for_time(cls, db: Session, start, end):
        """
        获取指定日期的告警记录
        """
        object_info = db.query(cls).filter(and_(
            cls.starts_at >= start,
            cls.starts_at <= end)
        ).order_by(cls.starts_at.desc()).to_dict()
        return object_info





